package com.fenghuajueli.idiomppp.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.fenghuajueli.idiomppp.R;
import com.fenghuajueli.idiomppp.entity.IdiomPinEntity;
import com.fenghuajueli.libbasecoreui.listener.OnBaseClick;
import com.fenghuajueli.libbasecoreui.listener.OnListClickListener;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IdiomGridAdapter extends BaseAdapter {

    private List<IdiomPinEntity> idiomPinEntityList;
    private Context mContext;
    private LayoutInflater mInflater;
    private int itemWidth;
    List<IdiomPinEntity> targetList;
    private int selectPosition = -1;
    private IdiomPinEntity currentSelectedEntity;
    private OnListClickListener<IdiomPinEntity> onSelectedListener;
    private List<IdiomPinEntity> loadFillIdiomList;//等待填充的文字集合
    private OnListClickListener<IdiomPinEntity> onSelectedCancelListener;
    private Map<Integer, List<IdiomPinEntity>> rowEqualMap = new HashMap<>();//行相同的词语
    private Map<Integer, List<IdiomPinEntity>> columnEqualMap = new HashMap<>();//列相同的词语
    private OnBaseClick<Integer> onSuccessListener;//全部成功的回调
    List<List<IdiomPinEntity>> successRowList;
    List<List<IdiomPinEntity>> successColumnList;
    private OnBaseClick<String> onSingleCheckRightListener;//单个检测成功的回调


    public IdiomGridAdapter(Context context, List<IdiomPinEntity> idiomPinEntityList, List<IdiomPinEntity> targetList, List<IdiomPinEntity> loadFillIdiomList) {
        this.idiomPinEntityList = idiomPinEntityList;
        this.mInflater = LayoutInflater.from(context);
        this.targetList = targetList;
        this.mContext = context;
        this.loadFillIdiomList = loadFillIdiomList;
        selectPosition = -1;
        for (int i = 0; i < 10; i++) {
            List<IdiomPinEntity> list = new ArrayList<>();
            for (int j = 0; j < 10; j++) {
                IdiomPinEntity idiomPinEntity = new IdiomPinEntity();
                idiomPinEntity.setRow(i);
                idiomPinEntity.setColumn(j);
                if (loadFillIdiomList.contains(idiomPinEntity)) {
                    list.add(loadFillIdiomList.get(loadFillIdiomList.indexOf(idiomPinEntity)));
                }
            }
            if (list.size() > 1) {
                rowEqualMap.put(i, list);
            }
        }
        for (int i = 0; i < 10; i++) {
            List<IdiomPinEntity> list = new ArrayList<>();
            for (int j = 0; j < 10; j++) {
                IdiomPinEntity idiomPinEntity = new IdiomPinEntity();
                idiomPinEntity.setRow(j);
                idiomPinEntity.setColumn(i);
                if (loadFillIdiomList.contains(idiomPinEntity)) {
                    list.add(loadFillIdiomList.get(loadFillIdiomList.indexOf(idiomPinEntity)));
                }
            }
            if (list.size() > 1) {
                columnEqualMap.put(i, list);
            }
        }

        for (int i = 0; i < loadFillIdiomList.size(); i++) {
            if (targetList.contains(loadFillIdiomList.get(i))) {
                IdiomPinEntity idiomPinEntity = targetList.get(targetList.indexOf(loadFillIdiomList.get(i)));
                if (!idiomPinEntity.getFill()) {
                    selectPosition = idiomPinEntityList.indexOf(idiomPinEntity);
                    currentSelectedEntity = idiomPinEntity;
                    LogUtils.d("初始化第一个填充的位置：" + selectPosition, GsonUtils.toJson(currentSelectedEntity));
                    break;
                }
            }
        }
        nextFillPosition();
        itemWidth = (ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(94)) / 10;
    }

    public void refreshData(List<IdiomPinEntity> idiomPinEntityList, List<IdiomPinEntity> targetList, List<IdiomPinEntity> loadFillIdiomList) {
        this.idiomPinEntityList = idiomPinEntityList;
        this.targetList = targetList;
        this.loadFillIdiomList = loadFillIdiomList;
        selectPosition = -1;
        for (int i = 0; i < loadFillIdiomList.size(); i++) {
            if (targetList.contains(loadFillIdiomList.get(i))) {
                IdiomPinEntity idiomPinEntity = targetList.get(targetList.indexOf(loadFillIdiomList.get(i)));
                if (!idiomPinEntity.getFill()) {
                    selectPosition = idiomPinEntityList.indexOf(idiomPinEntity);
                    currentSelectedEntity = idiomPinEntity;
                    break;
                }
            }
        }
        nextFillPosition();
        notifyDataSetChanged();
    }

    public void setOnSingleCheckRightListener(OnBaseClick<String> onSingleCheckRightListener) {
        this.onSingleCheckRightListener = onSingleCheckRightListener;
    }

    public void setOnSuccessListener(OnBaseClick<Integer> onSuccessListener) {
        this.onSuccessListener = onSuccessListener;
    }

    public void setSuccessRowList(List<List<IdiomPinEntity>> successRowList) {
        this.successRowList = successRowList;
    }

    public void setSuccessColumnList(List<List<IdiomPinEntity>> successColumnList) {
        this.successColumnList = successColumnList;
    }

    @Override
    public int getCount() {
        return idiomPinEntityList.size();
    }

    @Override
    public Object getItem(int i) {
        return idiomPinEntityList.get(i);
    }

    public void setOnSelectedListener(OnListClickListener<IdiomPinEntity> onSelectedListener) {
        this.onSelectedListener = onSelectedListener;
    }

    public void setOnSelectedCancelListener(OnListClickListener<IdiomPinEntity> onSelectedCancelListener) {
        this.onSelectedCancelListener = onSelectedCancelListener;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.idiom_item_layout, null);
            holder.idiomText = convertView.findViewById(R.id.idiomText);
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(itemWidth, itemWidth);
            convertView.setLayoutParams(layoutParams);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        IdiomPinEntity idiomPinEntity = idiomPinEntityList.get(position);
        if (targetList.contains(idiomPinEntity)) {
            int index = targetList.indexOf(idiomPinEntity);
            IdiomPinEntity target = targetList.get(index);
            if (target.getStatus() < 0) {
                holder.idiomText.setBackgroundResource(R.mipmap.aa_btn_bg_nor_chengyu);
                holder.idiomText.setText("");
                holder.idiomText.setOnClickListener(null);
            } else {
                if (target.getStatus() == 1) {
                    holder.idiomText.setBackgroundResource(R.mipmap.aa_btn_guanqia_on1);
                    holder.idiomText.setText(target.getWord());
                    holder.idiomText.setOnClickListener(null);
                } else if (target.getStatus() == 0) {
                    if (target.getFill()) {
                        //已经手动填充过，再次点击时要取消
                        holder.idiomText.setBackgroundResource(R.mipmap.aa_btn_guanqia_on1);
                        holder.idiomText.setText(target.getFillText());
                        holder.idiomText.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
//                                if (!QuickClickUtils.isFastClick()) {
//                                    return;
//                                }
                                selectPosition = position;
                                currentSelectedEntity = target;
                                onSelectedCancelListener.itemClick(position, target);
                                target.setFill(false);
                                target.setFillText("");
                                notifyDataSetChanged();
                            }
                        });
                    } else {
                        holder.idiomText.setText("");
                        holder.idiomText.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                selectPosition = position;
                                currentSelectedEntity = target;
                                onSelectedListener.itemClick(position, target);
                                notifyDataSetChanged();
                            }
                        });
                        if (selectPosition == position) {
                            holder.idiomText.setBackgroundResource(R.mipmap.aa_bg_chengyu_sel);
                        } else {
                            holder.idiomText.setBackgroundResource(R.mipmap.aa_btn_guanqia_on1);
                        }
                    }
                } else {
                    holder.idiomText.setBackgroundResource(R.mipmap.aa_btn_bg_nor_chengyu);
                    holder.idiomText.setText("");
                    holder.idiomText.setOnClickListener(null);
                }
            }
        } else {
            holder.idiomText.setBackgroundResource(R.mipmap.aa_btn_bg_nor_chengyu);
            holder.idiomText.setText("");
            holder.idiomText.setOnClickListener(null);
        }
        return convertView;
    }

    public int getSelectPosition() {
        return selectPosition;
    }


    public IdiomPinEntity getCurrentSelectedEntity() {
        return currentSelectedEntity;
    }


    public void fillText(String text) {
        currentSelectedEntity.setFill(true);
        currentSelectedEntity.setFillText(text);
        notifyDataSetChanged();
        //先判断当前填充的这个有没有正确
        checkSingleSuccess();
        nextFillPosition();
    }

    /**
     * 判断有没有存在一个已经填充正确的成语
     */
    private void checkSingleSuccess() {

        for (int i = 0; i < successRowList.size(); i++) {
            List<IdiomPinEntity> idiomPinEntities = successRowList.get(i);
            if (idiomPinEntities.contains(currentSelectedEntity)) {
                int rightCount = 0;
                int allFillTextCount = getAllFillCount(idiomPinEntities);
                String word = "";
                for (int j = 0; j < idiomPinEntities.size(); j++) {
                    IdiomPinEntity targetEntity = targetList.get(targetList.indexOf(idiomPinEntities.get(j)));
                    word = word + targetEntity.getWord();
                    if (targetEntity.getStatus() == 0) {
                        if (targetEntity.getWord().equals(targetEntity.getFillText())) {
                            rightCount++;
                        }
                    }
                }
                if (rightCount == allFillTextCount) {
                    onSingleCheckRightListener.onClick(word);
                }
            }
        }
        for (int i = 0; i < successColumnList.size(); i++) {
            List<IdiomPinEntity> idiomPinEntities = successColumnList.get(i);
            if (idiomPinEntities.contains(currentSelectedEntity)) {
                int rightCount = 0;
                int allFillTextCount = getAllFillCount(idiomPinEntities);
                String word = "";
                for (int j = 0; j < idiomPinEntities.size(); j++) {
                    IdiomPinEntity targetEntity = targetList.get(targetList.indexOf(idiomPinEntities.get(j)));
                    word = word + targetEntity.getWord();
                    if (targetEntity.getStatus() == 0) {
                        if (targetEntity.getWord().equals(targetEntity.getFillText())) {
                            rightCount++;
                        }
                    }
                }
                if (rightCount == allFillTextCount) {
                    onSingleCheckRightListener.onClick(word);
                }
            }
        }

    }

    /**
     * 获取需要填充的文字个数
     *
     * @return
     */
    private int getAllFillCount(List<IdiomPinEntity> idiomPinEntities) {
        int count = 0;
        for (int i = 0; i < idiomPinEntities.size(); i++) {
            if (idiomPinEntities.get(i).getStatus() == 0) {
                count++;
            }
        }
        return count;
    }


    /**
     * 移动到下一个填充的位置
     */
    private void nextFillPosition() {
        boolean isNext = false;
        //区分出每个成语，跳到下一个填充位时按照顺序跳转,先找出行或列相同的词语，判断这一行 或者一列词语是否已经填充完，没有者继续在这一行或这一列跳转
        if (rowEqualMap.containsKey(currentSelectedEntity.getRow())) {
            //存在于行相同的数据里
            LogUtils.d("存在于行相同的数据里---------------------");
            List<IdiomPinEntity> idiomPinEntities = rowEqualMap.get(currentSelectedEntity.getRow());
            Collections.sort(idiomPinEntities, new Comparator<IdiomPinEntity>() {
                @Override
                public int compare(IdiomPinEntity idiomPinEntity, IdiomPinEntity t1) {
                    int diff = idiomPinEntity.getRow() - t1.getRow();
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    }
                    return 0;
                }
            });
            for (int i = 0; i < idiomPinEntities.size(); i++) {
                IdiomPinEntity idiomPinEntity = loadFillIdiomList.get(loadFillIdiomList.indexOf(idiomPinEntities.get(i)));
                if (!idiomPinEntity.getFill()) {
                    selectPosition = idiomPinEntityList.indexOf(idiomPinEntity);
                    currentSelectedEntity = idiomPinEntity;
                    LogUtils.d("下一个要填充的数据：", GsonUtils.toJson(currentSelectedEntity));
                    isNext = true;
                    break;
                }
            }
        } else if (columnEqualMap.containsKey(currentSelectedEntity.getColumn())) {
            List<IdiomPinEntity> idiomPinEntities = columnEqualMap.get(currentSelectedEntity.getColumn());
            Collections.sort(idiomPinEntities, new Comparator<IdiomPinEntity>() {
                @Override
                public int compare(IdiomPinEntity idiomPinEntity, IdiomPinEntity t1) {
                    int diff = idiomPinEntity.getColumn() - t1.getColumn();
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    }
                    return 0;
                }
            });
            for (int i = 0; i < idiomPinEntities.size(); i++) {
                IdiomPinEntity idiomPinEntity = loadFillIdiomList.get(loadFillIdiomList.indexOf(idiomPinEntities.get(i)));
                if (!idiomPinEntity.getFill()) {
                    selectPosition = idiomPinEntityList.indexOf(idiomPinEntity);
                    currentSelectedEntity = idiomPinEntity;
                    LogUtils.d("下一个要填充的数据：", GsonUtils.toJson(currentSelectedEntity));
                    isNext = true;
                    break;
                }
            }
        }
        if (!isNext) {
            for (int i = 0; i < loadFillIdiomList.size(); i++) {
                if (targetList.contains(loadFillIdiomList.get(i))) {
                    IdiomPinEntity idiomPinEntity = targetList.get(targetList.indexOf(loadFillIdiomList.get(i)));
                    if (!idiomPinEntity.getFill()) {
                        selectPosition = idiomPinEntityList.indexOf(idiomPinEntity);
                        currentSelectedEntity = idiomPinEntity;
                        isNext = true;
                        break;
                    }
                }
            }
        }
        if (!isNext) {
            //不存在需要填充的单词了
            int rightTextCount = 0;
            for (int i = 0; i < targetList.size(); i++) {
                IdiomPinEntity idiomPinEntity = targetList.get(i);
                if (idiomPinEntity.getStatus() == 0) {
                    if (idiomPinEntity.getWord().equals(idiomPinEntity.getFillText())) {
                        rightTextCount++;
                    }
                }
            }
            LogUtils.d("正确的个数：" + rightTextCount, "需要填充的个数：" + (loadFillIdiomList.size()));
            if (rightTextCount == loadFillIdiomList.size()) {
                onSuccessListener.onClick(0);
            } else {
                //ToastUtils.showShort("检测完毕，有部分错误");
            }
        }
        notifyDataSetChanged();
    }


    final class ViewHolder {
        TextView idiomText;
    }

}
